import { defineStore } from 'pinia';
import { reactive, ref } from 'vue';

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem('token') || null); // 用户 toke
    const userInfo = reactive({}); // 用户信息

    // 设置token
    const setToken = (newToken) => {
        token.value = newToken;
        localStorage.setItem('token', newToken); // 将token存储到本地
    };
    // 获取token
    const getToken = () => {
        return token.value;
    }
    // 设置用户信息
    const setUserInfo = (newUserInfo) => {
        Object.assign(userInfo, newUserInfo);
    };
    // 获取用户信息
    const getUserInfo = () => {
        return userInfo.value;
    }
    // 清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {};
        localStorage.removeItem('userInfo'); // 清除本地存储的用户信息
    }
    // 请除token
    const clearToken = () => {
        token.value = null;
        localStorage.removeItem('token'); // 清除本地存储的token
        clearUserInfo(); // 清除用户信息
    }
    return {
        token,
        userInfo,
        setToken,
        getToken,
        setUserInfo,
        getUserInfo,
        clearUserInfo,
        clearToken
    };
})